/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.exception.AttachHasRemovedException;
import com.fujitsu.nanjing.tieba.ibator.CoreAttach;
import com.fujitsu.nanjing.tieba.service.AttachService;

/**
 * AttachController.java
 * 
 * @author Administrator
 */
@Controller
@RequestMapping("/attach")
public class AttachController extends BaseController {
	@Resource
	private AttachService attachService;
	@RequestMapping(value = "/{attachId}", method = RequestMethod.GET)
	public void download(Model model, HttpServletRequest request,
			HttpServletResponse response, @PathVariable String attachId)
			throws AttachHasRemovedException {
		attachId = decrypt(attachId);
		CoreAttach attach = attachService.findById(attachId);
		if (attach != null) {
			try {
				initWebRoot();
				downloadFile(null, attach.getFilename(),
						attachService.getContent(attach), response);
				attachService.incDownloads(attach);
			} catch (IOException e) {
				e.printStackTrace();
				throw new AttachHasRemovedException("附件不存在或已删除！");
			}
		}
	}
	@RequestMapping(value = "/{attachId}/inline", method = RequestMethod.GET)
	public void downloadPicture(Model model, HttpServletRequest request,
			HttpServletResponse response, @PathVariable String attachId) {
		attachId = decrypt(attachId);
		CoreAttach attach = attachService.findById(attachId);
		if (attach != null) {
			try {
				initWebRoot();
				download(null, INLINE, attach.getFilename(),
						attachService.getContent(attach), response);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
